<template>
  <McLayout class="container">
    <McHeader :title="'MateChat'" :logoImg="'https://matechat.gitcode.com/logo.svg'">
      <template #operationArea>
        <div class="operations">
          <i class="icon-helping"></i>
        </div>
      </template>
    </McHeader>
    <McLayoutContent v-if="startPage"
      style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px">
      <McIntroduction :logoImg="'https://matechat.gitcode.com/logo2x.svg'" :title="'MateChat'"
        :subTitle="'Hi，欢迎使用 MateChat'" :description="description"></McIntroduction>
      <McPrompt :list="introPrompt.list" :direction="introPrompt.direction" class="intro-prompt"
        @itemClick="onSubmit($event.label)"></McPrompt>
    </McLayoutContent>
    <McLayoutContent class="content-container" v-else>
      <template v-for="(msg, idx) in messages" :key="idx">
        <McBubble v-if="msg.from === 'user'" :content="msg.content" :align="'right'"
          :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg' }">
        </McBubble>
        
        <McBubble v-else :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/logo.svg' }">
          <McMarkdownCard :content="msg.content" :theme="theme" ></McMarkdownCard>
        </McBubble>
      </template>
    </McLayoutContent>
    <div class="shortcut" style="display: flex; align-items: center; gap: 8px">
      <McPrompt v-if="!startPage" :list="simplePrompt" :direction="'horizontal'" style="flex: 1"
        @itemClick="onSubmit($event.label)"></McPrompt>
      <Button style="margin-left: auto" icon="add" shape="circle" title="新建对话" size="md" @click="newConversation" />
    </div>
    <McLayoutSender>
      <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
            </div>
            <div class="input-foot-right">
              <Button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''"><span
                  class="demo-button-content">清空输入</span></Button>
            </div>
          </div>
        </template>
      </McInput>
    </McLayoutSender>
  </McLayout>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Button, DIcon } from 'vue-devui/button';  // 新增导入 DIcon
import 'vue-devui/button/style.css';
const theme = ref('light');
const description = [
  'MateChat 可以辅助研发人员编码、查询知识和相关作业信息、编写文档等。',
  '作为AI模型，MateChat 提供的答案可能不总是确定或准确的，但您的反馈可以帮助 MateChat 做的更好。',
];
const introPrompt = {
  direction: 'horizontal',
  list: [
    {
      value: 'quickSort',
      label: '帮我写一个快速排序',
      iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
      desc: '使用 js 实现一个快速排序',
    },
    {
      value: 'helpMd',
      label: '你可以帮我做些什么？',
      iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
      desc: '了解当前大模型可以帮你做的事',
    },
    {
      value: 'bindProjectSpace',
      label: '询问班级上课表',
      iconConfig: { name: 'icon-priority', color: '#3ac295' },
      desc: '1班星期4上什么课',
    },
  ],
};
const simplePrompt = [
  {
    value: 'quickSort',
    iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
    label: '帮我写一个快速排序',
  },
  {
    value: 'helpMd',
    iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
    label: '你可以帮我做些什么？',
  },
];
const startPage = ref(true);
const inputValue = ref('');

const messages = ref < any[] > ([]);

const newConversation = () => {
  startPage.value = true;
  messages.value = [];
}

const onSubmit = async (evt) => {
  const userMessage = typeof evt === 'string' ? evt : inputValue.value;
  if (!userMessage.trim()) return;

  inputValue.value = '';
  startPage.value = false;
  // 用户发送消息
  messages.value.push({
    from: 'user',
    content: userMessage,
  });

  const aiMessage = { from: 'model', content: '' };
  messages.value.push(aiMessage);

  try {
    const response = await fetch('/api/chat/ask', {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain'
      },
      body: userMessage,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body!.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      buffer += decoder.decode(value, { stream: true });

      // 关键修改：按 "}" 分割完整的JSON对象（假设每个JSON块以 "}" 结尾）
      const jsonChunks: string[] = [];
      let lastEnd = 0;
      for (let i = 0; i < buffer.length; i++) {
        if (buffer[i] === '}') {
          const chunk = buffer.substring(lastEnd, i + 1); // 截取从上次结束到当前 "}" 的内容
          if (chunk.trim().startsWith('{')) { // 确保是有效的JSON开头
            jsonChunks.push(chunk);
          }
          lastEnd = i + 1; // 更新结束位置
        }
      }
      buffer = buffer.substring(lastEnd); // 剩余未处理的部分

      for (const chunk of jsonChunks) {
        try {
          const parsedChunk = JSON.parse(chunk);
          aiMessage.content += parsedChunk.response;
          messages.value = [...messages.value];

          if (parsedChunk.done) {
            reader.cancel();
            return;
          }
        } catch (parseError) {
          console.error('JSON解析失败，内容:', chunk, '错误:', parseError);
        }
      }
    }

    // 处理最后可能剩余的内容（流结束时）
    if (buffer.trim()) {
      console.warn('未完全解析的剩余内容:', buffer);
    }

  } catch (error) {
    console.error('Error fetching AI response:', error);
    aiMessage.content = '抱歉，无法连接到AI服务，请稍后再试。';
    messages.value = [...messages.value];
  }
};
</script>

<style>
.container {
  max-width: 1000px;  /* 改为最大宽度适配小屏幕 */
  width: 95%;         /* 小屏幕时留边距 */
  margin: 20px auto;
  height: calc(90vh - 82px);
  padding: 20px;
  gap: 16px;          /* 增大模块间距 */
  background: #f8f9fa; /* 浅灰背景更柔和 */
  border: 1px solid #e9ecef; /* 更浅的边框色 */
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); /* 添加柔和阴影 */
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;          /* 增大消息间距 */
  overflow-y: auto;   /* 仅垂直滚动 */
  padding: 16px;      /* 内容区添加内边距 */
  background: #ffffff; /* 消息区纯白背景 */
  border-radius: 8px; /* 消息区圆角 */
  border: 1px solid #f0f2f5; /* 消息区浅边框 */
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;
}

.input-foot-wrapper .input-foot-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-foot-wrapper .input-foot-left span {
  font-size: 14px;
  line-height: 18px;
  color: #252b3a;
  cursor: pointer;
}

.input-foot-wrapper .input-foot-left .input-foot-dividing-line {
  width: 1px;
  height: 14px;
  background-color: #d7d8da;
}

.input-foot-wrapper .input-foot-left .input-foot-maxlength {
  font-size: 14px;
  color: #71757f;
}

.input-foot-wrapper .input-foot-right .demo-button-content {
  font-size: 14px;
}

.input-foot-wrapper .input-foot-right>*:not(:first-child) {
  margin-left: 8px;
}
input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;
  gap: 12px;  /* 增大元素间距 */
}

.input-foot-right Button {
  transition: all 0.2s; /* 添加过渡动画 */
}

.input-foot-right Button:hover {
  background: #f5f7fa; /* 悬停背景色 */
}

.input-foot-right Button:active {
  transform: scale(0.95); /* 点击微缩效果 */
}
@media (max-width: 768px) {
  .container {
    margin: 10px auto;
    padding: 12px;
    height: calc(100vh - 60px);
  }

  .content-container {
    padding: 12px;
  }

  .input-foot-maxlength {
    font-size: 12px; /* 小屏幕文字缩小 */
  }
}
McBubble[align="right"] .mc-bubble-content {
  background: #5e7ce0;  /* 品牌色背景 */
  color: #ffffff;       /* 白色文字 */
  border-radius: 12px 12px 4px 12px; /* 不对称圆角更自然 */
}

/* 模型消息气泡（左侧） */
McBubble:not([align="right"]) .mc-bubble-content {
  background: #ffffff;  /* 纯白背景 */
  color: #252b3a;       /* 深灰文字 */
  border: 1px solid #e9ecef; /* 浅边框 */
  border-radius: 12px 12px 12px 4px; /* 不对称圆角 */
}
</style>